import request from '@/utils/request'
import { removeLocalHistories, setLocalHistories } from '@/utils/storage'
import { RootThunkAction } from '..'
import { SearchAction } from '../reducers/search'
/**
 * 获取联想建议
 * @param keyword
 * @returns
 */
type SuggestListRes = {
  options: string[]
}
export const getSuggestList = (keyword: string): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<SuggestListRes>('/suggestion?q=' + keyword)
    if (!res.data.options[0]) {
      res.data.options = []
    }
    // console.log(res)
    dispatch({
      type: 'search/saveSuggestions',
      payload: res.data.options,
    })
  }
}
/**
 * 清空搜索结果
 * @returns
 */
export const clearSuggestions = (): SearchAction => {
  return {
    type: 'search/clearSuggestions',
  }
}
/**
 * 保存历史记录
 * @param keyWord
 * @returns
 */
export const saveHistioiesList = (keyWord: string): RootThunkAction => {
  return async (dispatch, getSate) => {
    // console.log(keyWord)
    // 获取到之前的histories
    let histories = getSate().search.histories
    // 不允许有重复的历史记录
    histories = histories.filter((item) => item !== keyWord)
    // 添加历史记录
    histories = [keyWord, ...histories]
    // 如果超过十条，就不要后面的
    if (histories.length > 10) {
      histories = histories.slice(0, 10)
    }
    // 保存到redux中
    dispatch({
      type: 'search/saveHistories',
      payload: histories,
    })
    // 保存到本地
    setLocalHistories(histories)
  }
}
/**
 * 清空历史记录
 * @returns
 */
export const clearHistories = (): RootThunkAction => {
  return async (dispatch) => {
    // 清空本地的历史记录
    removeLocalHistories()
    // 清空redux中的历史记录
    dispatch({
      type: 'search/clearHistories',
    })
  }
}
/**
 * 获取搜索结果
 */
export const getSearchResults = (keyWord: string, page: number): RootThunkAction => {
  return async (dispatch) => {
    const res = await request({
      method: 'GET',
      url: '/search',
      params: {
        page,
        q: keyWord,
        per_page: 10,
      },
    })
    // console.log(res)
    dispatch({
      type: 'search/saveSearchResults',
      payload: res.data.results,
    })
  }
}
